package com.itheima.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.bean.Employee;
import com.itheima.utils.BaseContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //可以在这里直接注入session对象，然后在下面获取到id值！
    //@Autowired
    //private HttpSession session;

    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        System.out.println("执行添加操作：mybatisplus来调用insertFill进行数据填充~！");

        //填充数据. 参数一：公共字段的属性名， 参数二： 给这个字段赋的值！
        metaObject.setValue("createTime" , LocalDateTime.now());
        metaObject.setValue("updateTime" , LocalDateTime.now());

        //Employee employee = (Employee) session.getAttribute("employee");

        //metaObject.setValue("createUser" , employee.getId());
        //metaObject.setValue("updateUser" , employee.getId());


        metaObject.setValue("createUser" , BaseContext.getCurrentId());
        metaObject.setValue("updateUser" , BaseContext.getCurrentId());
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        System.out.println("执行更新操作：mybatisplus来调用insertFill进行数据填充~！");


        metaObject.setValue("updateTime", LocalDateTime.now());

        //Employee employee = (Employee) session.getAttribute("employee");
        //metaObject.setValue("updateUser" , employee.getId());

        metaObject.setValue("updateUser" , BaseContext.getCurrentId());

    }
}
